<template>
    <el-dropdown trigger="click" placement="bottom-start" :hide-on-click="false">
        <span class="el-dropdown-link"
            ><i class="el-icon-s-grid"></i><i class="el-icon-arrow-down el-icon--right"></i
        ></span>
        <el-dropdown-menu slot="dropdown">
            <el-checkbox-group
                :min="1"
                @change="setCheckedColumns(checkedColumns, $event)"
                v-model="checkedColumns"
                class="table-columns-checkbox-group"
            >
                <el-dropdown-item v-for="(item, index) in showColumns" :key="index">
                    <el-checkbox @click.stop :label="item.value">{{ item.label }}</el-checkbox>
                </el-dropdown-item>
            </el-checkbox-group>
        </el-dropdown-menu>
    </el-dropdown>
</template>
<script>
// 当改变浏览器table列是保存已经选中的字段
export function setCheckedColumns(inputId, checkedColumns) {
    localStorage.setItem(inputId, checkedColumns.join(','));
}

export function getCheckedColumns(inputId, defaultValue) {
    const checkedColumns = localStorage.getItem(inputId);
    if (!checkedColumns) {
        return defaultValue || [];
    }
    return checkedColumns.split(',');
}

export default {
    name: 'checked-columns',
    props: {
        value: {
            type: Array,
            required: true
        },
        dataSource: {
            type: Array,
            required: true
        },
        // 唯一name
        checkedId: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            checkedColumns: []
        };
    },
    computed: {
        inputValue() {
            return this.value;
        },
        inputId() {
            return this.checkedId;
        },
        // 展示的列
        showColumns() {
            return this.dataSource;
        }
    },
    mounted() {
        this.checkedColumns = getCheckedColumns(this.inputId, this.inputValue);
        this.$emit('input', this.checkedColumns);
    },
    methods: {
        // 当改变浏览器table列是保存已经选中的字段
        setCheckedColumns(checkedColumns) {
            this.$emit('input', checkedColumns);
            setCheckedColumns(this.inputId, checkedColumns);
        }
    }
};
</script>

<style lang="scss" scoped>
.table-columns-checkbox-group {
    ::v-deep {
        .el-checkbox {
            display: block;
        }
    }
}
</style>
